import os
from PIL import Image, ImageFilter


class studentDatikaMeta:
    def __init__(self, name, studentId, frontPicDir, backPicDir):
        self.name = name
        self.id = studentId
        self.frontPicDir = frontPicDir
        self.backPicDir = backPicDir


if __name__ == '__main__':

    # 第一步：读取图片地址
    rawFolderPath = input(r'请输入答题卡文件夹地址。如“C:\Users\Admin\Desktop\3班(4653289)”')
    # rawFolderPath = r'C:\Users\Admin\Desktop\3班(4653289)'
    subjectName = input('请输入答题卡文件夹内的科目文件夹名称。如“数学”，“科学”')
    # subjectName = '数学'
    pinjieMode = input('请输入拼接方式，输入数字编号。1:两人一张A4纸。2:四人四宫格一张A4纸。')
    # pinjieMode = '1'
    isSharpen = input('是否启用锐化，输入数字编号。1：是。2：否')

    studentDatika = []
    for studentFolderName in os.listdir(rawFolderPath):
        try:
            thisStudentName = studentFolderName.split('(')[0]
            thisStudentId = studentFolderName.split('(')[1][:-1]
            studentFolderPath = os.path.join(rawFolderPath, studentFolderName) + '\\' + subjectName
            frontPicDir = studentFolderPath + '\\' + thisStudentName + '_1.png'
            backPicDir = studentFolderPath + '\\' + thisStudentName + '_2.png'
            thisStudentDatikaMeta = studentDatikaMeta(thisStudentName, thisStudentId, frontPicDir, backPicDir)
            studentDatika.append(thisStudentDatikaMeta)
        except Exception:
            pass

    if pinjieMode == '1':
        # 2张拼模式
        pending = []
        imagess = []
        for thisStudentDatika in studentDatika:
            pending.append(thisStudentDatika)
            if len(pending) == 2:
                # 读取图片
                image1 = Image.open(pending[0].frontPicDir)
                image2 = Image.open(pending[1].frontPicDir)
                print(pending[0].name)
                print(pending[1].name)
                # 判断是否需要旋转
                rwidth, rheight = image1.size
                if rwidth > rheight:
                    image1 = image1.rotate(90, expand=True)
                    image2 = image2.rotate(90, expand=True)
                    widthNow = rheight
                    heightNow = rwidth
                else:
                    widthNow = rwidth
                    heightNow = rheight

                # 创建拼接后的新画布
                new_width = widthNow * 2
                new_height = heightNow
                front_image = Image.new("RGB", (new_width, new_height))

                # 将两张图片拼接在新画布上
                front_image.paste(image1, (0, 0))
                front_image.paste(image2, (widthNow, 0))

                # 反面
                image2 = Image.open(pending[0].backPicDir)
                image1 = Image.open(pending[1].backPicDir)

                # 判断是否需要旋转
                if rwidth > rheight:
                    image1 = image1.rotate(270, expand=True)
                    image2 = image2.rotate(270, expand=True)
                    widthNow = rheight
                    heightNow = rwidth
                else:
                    widthNow = rwidth
                    heightNow = rheight

                # 创建拼接后的新画布
                new_width = widthNow * 2
                new_height = heightNow
                back_img = Image.new("RGB", (new_width, new_height))

                # 将2张图片拼接在新画布上
                back_img.paste(image1, (0, 0))
                back_img.paste(image2, (widthNow, 0))

                # 锐化
                if isSharpen == '1':
                    front_image = front_image.filter(ImageFilter.SHARPEN)
                    back_img = back_img.filter(ImageFilter.SHARPEN)
                else:
                    pass

                # 保存拼接后的图片
                imagess.append(front_image)
                imagess.append(back_img)
                pending = []
            else:
                pass
        if len(pending) > 0:
            # 加载初始答题卡
            imageReady =Image.open(pending[0].frontPicDir)

            # 判断是否需要旋转
            isNeedRotate = False
            rwidth, rheight = imageReady.size
            if rwidth > rheight:
                isNeedRotate = True
                widthNow = rheight
                heightNow = rwidth
            else:
                isNeedRotate = False
                widthNow = rwidth
                heightNow = rheight

            # 创建拼接后的新画布
            new_width = widthNow * 2
            new_height = heightNow
            front_image = Image.new("RGB", (new_width, new_height), color=(255, 255, 255))
            # front_imagePos = [(0, 0), (1, 0), (0, 1), (1, 1)]
            front_imagePos = [[0, 0], [1, 0]]

            back_img = Image.new("RGB", (new_width, new_height), color=(255, 255, 255))
            back_imgPos = [[1, 0], [0, 0]]

            index = 1

            for thisStudentDatika in pending:
                # 初始化答题卡
                imageNowFront = Image.open(thisStudentDatika.frontPicDir)
                imageNowBack = Image.open(thisStudentDatika.backPicDir)
                print(thisStudentDatika.name)

                # 旋转
                if isNeedRotate is True:
                    imageNowFront = imageNowFront.rotate(90, expand=True)
                    imageNowBack = imageNowBack.rotate(270, expand=True)

                # 拼图
                front_image.paste(imageNowFront, (front_imagePos[index-1][0]*widthNow, front_imagePos[index-1][1]*widthNow))
                back_img.paste(imageNowBack, (back_imgPos[index-1][0]*widthNow, back_imgPos[index-1][1]*widthNow))

                # 锐化
                if isSharpen == '1':
                    front_image = front_image.filter(ImageFilter.SHARPEN)
                    back_img = back_img.filter(ImageFilter.SHARPEN)
                else:
                    pass

                index += 1

            # 保存拼接后的图片
            imagess.append(front_image)
            imagess.append(back_img)

        imagess[0].save(rawFolderPath+'\\test.pdf', save_all=True, append_images=imagess[1:])
        print('打印时一定要选短边翻页,否则正反面学生将不匹配！可以先打印一张进行测试。')
        print('-----|-----|短|-----|-----')
        print('- A  |  B -|边|- B  |  A -')
        print('- A  |  B -|翻|- B  |  A -')
        print('-----|-----|页|-----|-----')
    else:
        # 4张拼接模式
        pending = []
        imagess = []
        for thisStudentDatika in studentDatika:
            pending.append(thisStudentDatika)
            if len(pending) == 4:
                # 加载答题卡
                image1 = Image.open(pending[0].frontPicDir)
                image2 = Image.open(pending[1].frontPicDir)
                image3 = Image.open(pending[2].frontPicDir)
                image4 = Image.open(pending[3].frontPicDir)
                print(pending[0].name)
                print(pending[1].name)
                print(pending[2].name)
                print(pending[3].name)

                # 判断是否需要旋转
                rwidth, rheight = image1.size
                if rwidth < rheight:
                    image1 = image1.rotate(90, expand=True)
                    image2 = image2.rotate(90, expand=True)
                    widthNow = rheight
                    heightNow = rwidth
                else:
                    widthNow = rwidth
                    heightNow = rheight

                # 创建拼接后的新画布
                new_width = widthNow * 2
                new_height = heightNow * 2
                front_image = Image.new("RGB", (new_width, new_height))

                # 将四张图片拼接在新画布上
                front_image.paste(image1, (0, 0))
                front_image.paste(image2, (widthNow, 0))
                front_image.paste(image3, (0, heightNow))
                front_image.paste(image4, (widthNow, heightNow))

                # 反面
                # 加载图片
                image2 = Image.open(pending[0].backPicDir)
                image1 = Image.open(pending[1].backPicDir)
                image4 = Image.open(pending[2].backPicDir)
                image3 = Image.open(pending[3].backPicDir)

                # 判断是否需要旋转
                rwidth, rheight = image1.size
                if rwidth < rheight:
                    image1 = image1.rotate(90, expand=True)
                    image2 = image2.rotate(90, expand=True)
                    widthNow = rheight
                    heightNow = rwidth
                else:
                    widthNow = rwidth
                    heightNow = rheight

                # 创建拼接后的新画布
                new_width = widthNow * 2
                new_height = heightNow * 2
                back_img = Image.new("RGB", (new_width, new_height))

                # 将四张图片拼接在新画布上
                back_img.paste(image1, (0, 0))
                back_img.paste(image2, (widthNow, 0))
                back_img.paste(image3, (0, heightNow))
                back_img.paste(image4, (widthNow, heightNow))

                imagess.append(front_image)
                imagess.append(back_img)
                pending = []
            else:
                pass
        if len(pending) > 0:
            # 加载初始答题卡
            imageReady =Image.open(pending[0].frontPicDir)

            # 判断是否需要旋转
            isNeedRotate = False
            rwidth, rheight = imageReady.size
            if rwidth < rheight:
                isNeedRotate = True
                widthNow = rheight
                heightNow = rwidth
            else:
                isNeedRotate = False
                widthNow = rwidth
                heightNow = rheight

            # 创建拼接后的新画布
            new_width = widthNow * 2
            new_height = heightNow * 2
            front_image = Image.new("RGB", (new_width, new_height), color=(255, 255, 255))
            front_imagePos = [[0, 0], [1, 0], [0, 1], [1, 1]]

            back_img = Image.new("RGB", (new_width, new_height), color=(255, 255, 255))
            back_imgPos = [[1, 0], [0, 0], [1, 1], [0, 1]]

            index = 1

            for thisStudentDatika in pending:
                # 初始化答题卡
                imageNowFront = Image.open(thisStudentDatika.frontPicDir)
                imageNowBack = Image.open(thisStudentDatika.backPicDir)
                print(thisStudentDatika.name)

                # 旋转
                if isNeedRotate is True:
                    imageNowFront = imageNowFront.rotate(90, expand=True)
                    imageNowBack = imageNowBack.rotate(270, expand=True)

                # 拼图
                front_image.paste(imageNowFront, (front_imagePos[index-1][0]*widthNow, front_imagePos[index-1][1]*heightNow))
                back_img.paste(imageNowBack, (back_imgPos[index-1][0]*widthNow, back_imgPos[index-1][1]*heightNow))

                # 锐化
                if isSharpen == '1':
                    front_image = front_image.filter(ImageFilter.SHARPEN)
                    back_img = back_img.filter(ImageFilter.SHARPEN)
                else:
                    pass

                index += 1

                # 保存拼接后的图片
            imagess.append(front_image)
            imagess.append(back_img)
        print('打印时一定要选短边翻页,否则正反面学生将不匹配！可以先打印一张进行测试。')
        print('-----|-----|短|-----|-----')
        print('- 1  |  2 -|边|- 2  |  1 -')
        print('- 3  |  4 -|翻|- 4  |  3 -')
        print('-----|-----|页|-----|-----')
        imagess[0].save(rawFolderPath + '\\test.pdf', save_all=True, append_images=imagess[1:])
    print('已完成!PDF文件在：', rawFolderPath+'\\test.pdf')
